import Taro, {Component} from '@tarojs/taro'
import {View,Image,Text} from '@tarojs/components'
import './addcut.scss'
import {getFoodCount,setFoodCount,getEvent} from '../../utils/common'
let myEvent = getEvent()
export default class AddCut extends Component {
    constructor () {
        super(...arguments);
        this.state = {
            num:0
        }
    }

    componentDidMount(){
        this.setState({num:getFoodCount(this.props.food)});
        myEvent.on("changeCata",()=>{
            //监听到菜品改变实现菜品数量的刷新
            this.setState({num:getFoodCount(this.props.food)});
        })
    }

    cutFood(){
        // this.props.food
        if(this.props.food){
            if(this.state.num > 0){
                myEvent.emit('addCut');
                setFoodCount(this.props.food,this.state.num,'cut',()=>{
                    this.setState({
                        num:getFoodCount(this.props.food)
                    })
                    myEvent.emit('addCut');
                })
            }else{
                console.error("num 等于 0")
            }
        }
    }

    addFood(){
        if(this.props.food){
            setFoodCount(this.props.food,this.state.num,'add',()=>{
                this.setState({
                    num:getFoodCount(this.props.food)
                });
                myEvent.emit('addCut');
            })
        }
    }
    render() {
        let {num} = this.state;
        let hideClass = num > 0 ? "":"hide";
        return (
            <View className ='addCut'>
                <Image onClick={this.cutFood.bind(this)} src={require('../../assets/img/cut.png')} className={'icon '+hideClass}></Image>
                <Text className={'num '+hideClass}>{num}</Text>
                <Image onClick={this.addFood.bind(this)} src={require('../../assets/img/add.png')} className='icon'></Image>
            </View>
        )
    }
}
